/*
 *
 *  Copyright (C) 2012-2024
 *  All rights reserved, Designed By 杭州连线客信息技术有限公司
 *  注意：
 *  本软件为杭州连线客信息技术有限公司开发研制，未经购买不得使用
 *  购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 *  一经发现盗用、分享等行为，将追究法律责任，后果自负
 *
 */

package org.dromara.web.service;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.lock.LockInfo;
import com.baomidou.lock.LockTemplate;
import com.baomidou.lock.executor.RedissonLockExecutor;
import com.lxk.event.ums.UmsUserCreateEvent;
import com.lxk.ums.domain.vo.UmsUserVo;
import com.lxk.ums.service.IUmsUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.constant.Constants;
import org.dromara.common.core.domain.model.RegisterBody;
import org.dromara.common.core.enums.LoginType;
import org.dromara.common.core.enums.UserType;
import org.dromara.common.core.exception.user.UserException;
import org.dromara.common.core.utils.MessageUtils;
import org.dromara.common.core.utils.SpringUtils;
import org.dromara.common.tenant.helper.TenantHelper;
import org.springframework.stereotype.Service;

/**
 * 注册校验方法
 *
 * @author Lion Li
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SysRegisterService {

    private final IUmsUserService umsUserService;
    private final SysLoginService loginService;
    private final LockTemplate lockTemplate;

    /**
     * 注册
     */
    public void register(RegisterBody registerBody) {
        String tenantId = registerBody.getTenantId();
        String username = registerBody.getUsername();
        String password = registerBody.getPassword();
        String confirmPassword = BCrypt.hashpw(registerBody.getConfirmPassword());
        String inviterCode = registerBody.getInviterCode();
        String registerDeviceType = registerBody.getRegisterDeviceType();
        // 校验用户类型是否存在
        String userType = UserType.getUserType(registerBody.getUserType()).getUserType();
        //校验密码跟确认密码是否相等
        loginService.checkLogin(
            LoginType.PASSWORD,
            tenantId,
            username,
            () -> !BCrypt.checkpw(password,confirmPassword));
        //创建用户
        Boolean b = this.registerUserByApp(tenantId, username ,confirmPassword, inviterCode ,registerDeviceType, userType);
        if(!b){
            throw new UserException("user.register.error");
        }
        loginService.recordLogininfor(tenantId, username, Constants.REGISTER, MessageUtils.message("user.register.success"));
//        boolean captchaEnabled = configService.selectCaptchaEnabled(tenantId);
//        // 验证码开关
//        if (captchaEnabled) {
//            validateCaptcha(tenantId, username, registerBody.getCode(), registerBody.getUuid());
////        }
//        SysUserBo sysUser = new SysUserBo();
//        sysUser.setUserName(username);
//        sysUser.setNickName(username);
//        sysUser.setPassword(BCrypt.hashpw(password));
//        sysUser.setUserType(userType);
//
//        boolean exist = TenantHelper.dynamic(tenantId, () -> {
//            return userMapper.exists(new LambdaQueryWrapper<SysUser>()
//                .eq(SysUser::getUserName, sysUser.getUserName()));
//        });
//        if (exist) {
//            throw new UserException("user.register.save.error", username);
//        }
//        boolean regFlag = userService.registerUser(sysUser, tenantId);
//        if (!regFlag) {
//            throw new UserException("user.register.error");
//        }
    }
    /**
     * 创建用户
     */
    private Boolean registerUserByApp(String tenantId, String username, String password,
                                      String inviterCode, String registerDeviceType,String userType){
        return TenantHelper.dynamic(tenantId, () -> {
            LockInfo lock = lockTemplate.lock(StrUtil.format("tenantId_{}_username_{}_usertype_{}", tenantId, username, userType),
                30000L, 5000L, RedissonLockExecutor.class);
            if (ObjectUtil.isNull(lock)) {
                log.warn("用户重复提交：{},{}", tenantId, username);
                throw new UserException("user.jcaptcha.error", username);
            }
            try {
                Opt<UmsUserVo> userByUserName = umsUserService.getUserByUserName(username);
                if (userByUserName.isPresent()) {
                    throw new UserException("user.register.save.error", username);
                }else {
                    // 注册一个新账号
                    UmsUserVo umsUserVo = umsUserService.registerUserByPhone(username,password, userType,
                        inviterCode, registerDeviceType, null, null);
                    // 用户创建
                    SpringUtils.publishEvent(new UmsUserCreateEvent().setUserId(umsUserVo.getId()).setUserType(umsUserVo.getUserType()));
                }
                return Boolean.TRUE;
            }finally {
                lockTemplate.releaseLock(lock);
            }
        });
    }
}
